package com.dp.appi.controller;

import com.dp.appi.entity.UserEntity;
import com.dp.appi.exception.CommonException;
import com.dp.appi.exception.OauthRuntimeException;
import com.dp.appi.exception.SendSMSException;
import com.dp.appi.service.ConsumerService;
import com.dp.appi.service.OauthService;
import com.dp.appi.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * Created by xiaoji on 2016/4/20.
 * 认证
 */
@Controller
@RequestMapping(value = "/oauthControl")
public class OauthControl {
    private static Logger log = LoggerFactory.getLogger(OauthControl.class);
    private static final String FORGET = "FORGET_";
    @Autowired
    private OauthService oauthService;

    @Autowired
    private ConsumerService consumerService;
    /**
     * 注册
     * @param modelMap 返回信息
     * @param username 注册用户
     * @param mobilePhone 用户手机
     * @param key 验证码前缀
     * @param ident_code 验证码
     * @param pwd 密码
     */
    @RequestMapping(value = "/regedit",method = RequestMethod.POST)
    public void regedit(ModelMap modelMap,String username,String mobilePhone,String key,String ident_code,String pwd) {
        try {
            //验证短信
            boolean boo = ValidCode.isCorrectValidCode(mobilePhone+"_"+key,ident_code);
            if(boo){
                oauthService.insertUser(username, mobilePhone, pwd);
                modelMap.addAllAttributes(SYS.SUCCESS.msgMap());
            }else{
                modelMap.addAllAttributes(SYS.SMS002.msgMap());
                return;
            }
        }catch (SendSMSException e){
            modelMap.addAllAttributes(SYS.valueOf(e.getMessage()).Msg);
        }catch (OauthRuntimeException e){
            modelMap.addAllAttributes(SYS.valueOf(e.getMessage()).Msg);
        }catch (Exception e) {
            modelMap.addAllAttributes(SYS.E10002.msgMap());
            log.error(ExceptionUtil.getExceptionAllinformation(e));
        }
    }


    /**
     * 设置密保问题
     * @param modelMap
     * @param param
     */
    @RequestMapping(value = "/setSecurityProblem",method = RequestMethod.POST)
    public void setSecurityProblem(ModelMap modelMap, @RequestParam Map<String,String> param) {
        try {
            String openIdent = param.get("openIdent");
            UserEntity userEntity = UserEntity.decrypt(openIdent);
            Map<String, Object> map = consumerService.getUser(userEntity);
           String id=String.valueOf(map.get("id"));
            String security_problem1 = param.get("security_problem1");
            String security_answer1 = param.get("security_answer1");
            String security_problem2 = param.get("security_problem2");
            String security_answer2 = param.get("security_answer2");
            if(StringUtils.isEmpty(security_problem1) || StringUtils.isEmpty(security_answer1)
                    || StringUtils.isEmpty(security_problem2) || StringUtils.isEmpty(security_answer2)){
                modelMap.addAllAttributes(SYS.OA009.msgMap());
            }else{
                oauthService.setSecurityProblem(id,security_problem1,security_answer1,security_problem2,security_answer2);
                modelMap.addAllAttributes(SYS.SUCCESS.msgMap());
            }
        }catch (Exception e) {
            modelMap.addAllAttributes(SYS.E10002.msgMap());
            log.error(ExceptionUtil.getExceptionAllinformation(e));
        }
    }

    /**
     * 登录
     * @param modelMap
     * @param username 账号
     * @param pwd 密码
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public void login(ModelMap modelMap,String username,String pwd) {
        try {
            if(StringUtils.isEmpty(username)){
                modelMap.addAllAttributes(SYS.OA006.msgMap());
                return;
            }
            if(StringUtils.isEmpty(pwd)){
                modelMap.addAllAttributes(SYS.OA007.msgMap());
                return;
            }

            Map<String,Object> map = oauthService.getUser(username);
            if(map == null){
                modelMap.addAllAttributes(SYS.L10005.msgMap());
                return;
            }
            String username2=String.valueOf(map.get("username"));//用这个来加密，前面的username可能是手机号码
            String password = String.valueOf(map.get("password"));//数据库加密过后的密码
            String pw2 = PasswordUtil.encrypt(username2, pwd, PasswordUtil.getStaticSalt());
            if(!password.equals(pw2)){
                modelMap.addAllAttributes(SYS.L10005.msgMap());
                return;
            }else{
                String status = String.valueOf(map.get("status"));
                if(status.equals("0")){//账户未被激活
                    modelMap.addAllAttributes(SYS.L10007.msgMap());
                    return;
                } else{
                    UserEntity userEntity = new UserEntity();
                    userEntity.setA(username2);
                    userEntity.setB(String.valueOf(map.get("mobilePhone")));
                    userEntity.setC(password);

                    String strTime = DateUtil.getNowDate("yyyyMMddHHmmss");

                    String openIdent=userEntity.getOpenIdent();
                    String openIdentuser =openIdent+strTime;
                    modelMap.addAttribute("openIdent",openIdent);
                    modelMap.addAttribute("openIdentuser",openIdentuser);
//                modelMap.addAllAttributes(SYS.SUCCESS.msgMap());
                    modelMap.addAttribute("user_id",map.get("id"));
                    modelMap.addAttribute("username",map.get("username"));
                    modelMap.addAttribute("mobilePhone",map.get("mobilePhone"));
                    modelMap.addAttribute("realname",map.get("realname"));
                    modelMap.addAttribute("avatar",map.get("avatar"));
                    modelMap.addAttribute("email",map.get("email"));
                    modelMap.addAttribute("qq",map.get("qq"));
                    modelMap.addAttribute("wx",map.get("wx"));
                    if(map.get("birthday") != null){
                        Date birthday = (Date)(map.get("birthday"));
                        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
                        modelMap.addAttribute("birthday",simpleDateFormat.format(birthday));
                    }
                    modelMap.addAttribute("sex",map.get("sex"));
                    modelMap.addAttribute("role",map.get("role"));
                    modelMap.addAttribute("company",map.get("company"));
                    Map<String,Object> partMap=consumerService.getTSpartByUserId(String.valueOf(map.get("id")));
                    if(partMap!=null){
                        modelMap.addAttribute("org_id",partMap.get("org_id"));
                        modelMap.addAttribute("org_type",partMap.get("org_type"));
                    }
                    if(Constant.loginmap.containsKey(map.get("id").toString()))
                    {
                        Constant.loginmap.remove(map.get("id").toString());
                    }
                    Constant.loginmap.put(map.get("id").toString(),openIdentuser);
                }
            }
        }catch (CommonException c) {
            modelMap.addAllAttributes(SYS.valueOf(c.getMessage()).msgMap());
        }catch (OauthRuntimeException e){
            modelMap.addAllAttributes(SYS.valueOf(e.getMessage()).Msg);
        }catch (Exception e) {
            e.printStackTrace();
            modelMap.addAllAttributes(SYS.E10002.msgMap());
            log.error(ExceptionUtil.getExceptionAllinformation(e));
        }
    }

    /**
     * 短信找回密码
     * @param modelMap
     * @param phone 用户账号
     * @param key 验证码前缀
     * @param ident_code 验证码
     */
    @RequestMapping(value = "/smsRetrieve",method = RequestMethod.POST)
    public void smsRetrieve(ModelMap modelMap,String phone,String key,String ident_code) {
        try {
            Map<String,Object> map = oauthService.getUser(phone);
            //查出账号
            if(map == null){
                modelMap.addAllAttributes(SYS.OA003.msgMap());
                return;
            }
            String mobilePhone = String.valueOf(map.get("mobilePhone"));
            String username2 = String.valueOf(map.get("username"));
            //验证短信
            boolean boo = ValidCode.isCorrectValidCode(mobilePhone+"_"+key,ident_code);
            if(boo){
                String token = MD5.getBASE64MD5(phone+key+ident_code+DateUtil.getCurrentDate());
                ValidCode.setValidCode(FORGET+phone,token);
                modelMap.addAttribute("token", token);
                return;
            }else{
                modelMap.addAllAttributes(SYS.SMS002.msgMap());
                return;
            }
        }catch (OauthRuntimeException e){
            modelMap.addAllAttributes(SYS.valueOf(e.getMessage()).Msg);
        }catch (Exception e) {
            modelMap.addAllAttributes(SYS.E10002.msgMap());
            log.error(ExceptionUtil.getExceptionAllinformation(e));
        }
    }

    /**
     * 获取密保问题
     * @param modelMap
     * @param username
     */
    @RequestMapping(value = "/getSecurityProblem",method = RequestMethod.GET)
    public void getSecurityProblem(ModelMap modelMap,String username){
        try{
            Map<String,Object> map = oauthService.getUser(username);
            //查出账号
            if(map == null){
                modelMap.addAllAttributes(SYS.OA003.msgMap());
                return;
            }
            if(StringUtils.isEmpty(map.get("security_problem1"))){
                modelMap.addAllAttributes(SYS.OA008.msgMap());
                return;
            }
            if(StringUtils.isEmpty(map.get("security_problem2"))){
                modelMap.addAllAttributes(SYS.OA008.msgMap());
                return;
            }
            modelMap.addAttribute("security_problem1",String.valueOf(map.get("security_problem1")));
            modelMap.addAttribute("security_problem2",String.valueOf(map.get("security_problem2")));
        }catch (OauthRuntimeException e){
            modelMap.addAllAttributes(SYS.valueOf(e.getMessage()).Msg);
        }catch (Exception e) {
            modelMap.addAllAttributes(SYS.E10002.msgMap());
            log.error(ExceptionUtil.getExceptionAllinformation(e));
        }
    }

    /**
     * 密保找回密码
     * @param modelMap
     * @param username 账号名称
     * @param security_answer1 答案1
     * @param security_answer2 答案2
     */
    @RequestMapping(value = "/securityRetrieve",method = RequestMethod.POST)
    public void securityRetrieve(ModelMap modelMap,String username,String security_answer1,String security_answer2){
        try{
            Map<String,Object> map = oauthService.getUser(username);
            //查出账号
            if(map == null){
                modelMap.addAllAttributes(SYS.OA003.msgMap());
                return;
            }
            String security_answer1db = String.valueOf(map.get("security_answer1"));
            String security_answer2db = String.valueOf(map.get("security_answer2"));
            if(StringUtils.isEmpty(security_answer1db) || StringUtils.isEmpty(security_answer2db)){
                modelMap.addAllAttributes(SYS.OA004.msgMap());
                return;
            }
            if(!security_answer1db.equals(security_answer1) || !security_answer2db.equals(security_answer2)){
                modelMap.addAllAttributes(SYS.OA005.msgMap());
                return;
            }else{
                String token = MD5.getBASE64MD5(username+security_answer1+security_answer2+DateUtil.getCurrentDate());
                ValidCode.setValidCode(FORGET+username,token);
                modelMap.addAttribute("token",token);
            }
        }catch (OauthRuntimeException e){
            modelMap.addAllAttributes(SYS.valueOf(e.getMessage()).Msg);
        }catch (Exception e) {
            modelMap.addAllAttributes(SYS.E10002.msgMap());
            log.error(ExceptionUtil.getExceptionAllinformation(e));
        }
    }

    /**
     * 修改密码
     * @param modelMap
     * @param phone 手机号码
     * @param key 验证码关键字
     * @param password 密码
     * @param validcode 验证码
     */
//    @RequestMapping(value = "/upPsd",method = RequestMethod.POST)
//    public void upPsd(ModelMap modelMap,String phone,String key,String password,String validcode){
//        try{
//            //验证短信
////            boolean boo = ValidCode.isCorrectValidCode(phone+"_"+key,validcode);
//            boolean boo = true;
//            if(boo){
//                Map<String,Object> map = oauthService.getUser(phone);
//                //查出账号
//                if(map == null){
//                    modelMap.addAllAttributes(SYS.OA003.msgMap());
//                    return;
//                }
//                //修改密码
//                String username2 = String.valueOf(map.get("username"));
//                oauthService.updatePwd(String.valueOf(map.get("id")),PasswordUtil.encrypt(password,username2,PasswordUtil.getStaticSalt()));
//                modelMap.addAllAttributes(SYS.SUCCESS.msgMap());
//            }else{
//                modelMap.addAllAttributes(SYS.SMS002.msgMap());
//                return;
//            }
//        }catch (SendSMSException e){
//            modelMap.addAllAttributes(SYS.valueOf(e.getMessage()).Msg);
//        }catch (OauthRuntimeException e){
//            modelMap.addAllAttributes(SYS.valueOf(e.getMessage()).Msg);
//        }catch (Exception e) {
//            modelMap.addAllAttributes(SYS.E10002.msgMap());
//            log.error(ExceptionUtil.getExceptionAllinformation(e));
//        }
//    }

    /**
     * 修改密码
     * @param modelMap
     * @param username 用户
     * @param token 令牌
     * @param password 密码
     */
    @RequestMapping(value = "/reUpPsd",method = RequestMethod.POST)
    public void reUpPsd(ModelMap modelMap,String username,String token,String password){
        try{
            //验证令牌
//            boolean boo = ValidCode.isCorrectValidCode(FORGET+username,token);
                boolean boo=true;
            if(boo){
                Map<String,Object> map = oauthService.getUser(username);
                //查出账号
                if(map == null){
                    modelMap.addAllAttributes(SYS.OA003.msgMap());
                    return;
                }
                //修改密码
                String username2 = String.valueOf(map.get("username"));
                String password2 = PasswordUtil.encrypt(username2,password,PasswordUtil.getStaticSalt());
                oauthService.updatePwd(String.valueOf(map.get("id")),password2);
                UserEntity userEntity = new UserEntity();
                userEntity.setA(username2);
                userEntity.setB(String.valueOf(map.get("mobilePhone")));
                userEntity.setC(password2);
                modelMap.addAttribute("openIdent",userEntity.getOpenIdent());
                modelMap.addAllAttributes(SYS.SUCCESS.msgMap());
            }else{
                modelMap.addAllAttributes(SYS.SMS004.msgMap());
                return;
            }
        }catch (SendSMSException e){
            modelMap.addAllAttributes(SYS.valueOf(e.getMessage()).Msg);
        }catch (OauthRuntimeException e){
            modelMap.addAllAttributes(SYS.valueOf(e.getMessage()).Msg);
        }catch (Exception e) {
            modelMap.addAllAttributes(SYS.E10002.msgMap());
            log.error(ExceptionUtil.getExceptionAllinformation(e));
        }
    }
}
